package com.ydl.partitionscheduler.builder;

import com.ydl.partitionscheduler.config.TablePartitionProperties;
import com.ydl.partitionscheduler.model.PartitionInfo;
import org.springframework.stereotype.Component;

@Component
public class OraclePartitionBuilder implements PartitionStatementBuilder {

    @Override
    public String buildCreateStatement(TablePartitionProperties.TablePartitionConfig config, PartitionInfo partition) {
        return String.format(
                "ALTER TABLE %s ADD PARTITION %s VALUES LESS THAN (TO_DATE('%s', '%s'))",
                config.getMainTable(),
                partition.getPartitionName(),
                partition.getEndValue(),
                getOracleDateFormat(config.getValuePattern())
        );
    }

    @Override
    public String buildExistsStatement(String mainTable, String partitionName) {
        return String.format("SELECT COUNT(1) FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_NAME = '%s' AND PARTITION_NAME = '%s'", mainTable, partitionName);
    }

    private String getOracleDateFormat(String pattern) {
        return pattern.replace("yyyy", "YYYY")
                .replace("MM", "MM")
                .replace("dd", "DD");
    }

    @Override
    public boolean supports(String databaseProductName) {
        return databaseProductName.toLowerCase().contains("oracle");
    }
}
